package com.vast.ui.component.socketinterface.server;

import java.net.ServerSocket;
import java.net.Socket;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


import com.vast.ui.component.socketinterface.request.RequestQueue;
import com.vast.ui.component.state.Sequence;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;

public final class SendService implements SocketService {
	 //private final ExecutorService executorService = Executors.newCachedThreadPool();
	 private String                pluginId;
	 private ExecutorService       executorService;// = Executors.newSingleThreadExecutor();
	 private ServerSocket          serverSendSocket = null;
	 private Socket                clientSendSocket = null;
	 private final Sequence        sequence;
	 private final RequestQueue    sendQueue;
	 private final Logger          logger;
	 
	 public SendService(String pluginId, Sequence sequence, RequestQueue  sendQueue) {
		 this.pluginId  = pluginId;
		 this.sequence  = sequence;
	     this.sendQueue = sendQueue;
	     this.logger        = ConsoleLoggerSingleton.getInstance();
	 }

     public void run() {
    	 if (!serverSendSocket.isClosed()) {
             try {
            	 clientSendSocket = serverSendSocket.accept();
                 logger.writeEntry(pluginId + ": Send socket is accepted.");
                 this.executorService = Executors.newCachedThreadPool();
                 executorService.execute(new SendHandler(pluginId, clientSendSocket, sequence, sendQueue));
             } catch (Exception e) {
                 //e.printStackTrace();
             }
         }
     }
     
     public void startup(int port) {
         if (serverSendSocket == null || serverSendSocket.isClosed()) {
             try {
            	 serverSendSocket = new ServerSocket(port);
                 new Thread(this).start();
                 logger.writeEntry(pluginId + ": Start Send Service. (port: " + port + ")");
             } catch (Exception e) {
                 try {
                	 serverSendSocket.close();
                 } catch (Exception e2) {}
                 logger.writeEntry(pluginId + ": Can not launch Send Service.");
             }
         } else {
        	 logger.writeEntry(pluginId + ": Send Service is runnning.");
         }
     }
     
     public void shutdown() {
    	 executorService.shutdownNow();
         if (serverSendSocket != null && !serverSendSocket.isClosed()) {
             try {
            	 serverSendSocket.close();
            	 logger.writeEntry(pluginId + ": Send service is stopped.");
             } catch (Exception e) {}
         } else {
        	 logger.writeEntry(pluginId + ": Send channel is not working.");
         }
     }
	 
}
